package cn.tedu.sp02.item.controller;

import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.sp01.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {

    @Value("${server.port}")
    private Integer port;

    @Autowired
    private ItemService itemService;


    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId){
        log.info("获取订单的商品列表，orderId="+orderId);

        if (Math.random()<0.9){
            try{
                long seconds=new Random().nextInt(5000);
                log.info("延迟时间："+seconds);
                Thread.sleep(seconds);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }


        List<Item> items = itemService.getItems(orderId);
        return JsonResult.ok().msg("port="+port).data(items);
    }

    @PostMapping("/decreaseNumber")
//    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }

}
